<script lang="ts" setup>
import type { StateType } from './types';

import { computed,defineProps } from 'vue';
import { useRoute } from 'vue-router';
import { $t } from '@vben/locales';
import { Page ,z} from '@vben/common-ui';
import { useTabs } from '@vben/hooks';

import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Select,
  SelectOption,
  TabPane,
  Tabs,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { pinyin } from 'pinyin-pro';

import { useVbenForm } from '#/adapter/form';
import { getPageInfo_vechile, postPage_vechile, putPage_vechile } from '#/api/portal/home';
import { usePreferencesStore } from '#/store';
import {  getPage } from '#/api/admin/themefile';
import { getPage as getNews } from '#/api/portal/news';
import { getArticle } from '#/api/portal/article';
import { useVbenModal } from '@vben/common-ui';


const index = ref<number>(0); // 外层定义
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  footer: false,
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values1: { id?: number } = formModalApi.getData();
      index.value = values1.id ?? 0; // 给外层的 index 赋值
      if(index.value>0){
             await onGetPage(index.value);
      }
      
    }
  },
 
});




const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

// const index: any = computed(() => {
//   return route.params?.id ?? -1;
// });
const router = useRouter();

const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
// const pageTitle =
//   Number.parseInt(index.value, 10) === 0
//     ? $t('page.common.Add')+` ${routeTitle}`
//     : `No.${index.value} - `+$t('page.common.Edit')+` ${routeTitle}`;
// setTabTitle(pageTitle);
// useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    title: '',
    discover: '',
    des: '',
    categoey:'',
    link:'',
   
  },
  pageThemeFiles: [],
});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  resetButtonOptions: {
    show: false,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    
    },
    {
      component: 'Textarea',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.title;
          state.form.title = values.title;
          state.form.models = values.models;
          state.form.images = values.images;
          state.form.des = values.des;
          state.form.link = values.link;
          state.form.discover = values.discover;
          state.form.category = values.category
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'title',
          'images',
          'des',
          'discover',
          'models',
          'link',
          'categoey',
        ],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter')+' ('+$t('admin.maxChars', { length: 100 })+'）',
      },
      fieldName: 'title',
      label: `${routeTitle} `+$t('page.common.Title'),
      rules: z.string().max(100,$t('admin.maxChars', { length: 100 })),
    },
    {
        component: 'Select',
        defaultValue: '',
        componentProps: {
            class: 'w-full',
             options: [
                {
                    label: 'ATV',
                    value: 'ATV',
                },
                {
                    label: 'SXS',
                    value:  'SXS',
                },
             ]
        },
        fieldName: 'category',
        label: $t('page.common.Category'),
    },

  
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter')+' ('+$t('admin.maxChars', { length: 250 })+'）',
      },
      fieldName: 'des',
      label: `${routeTitle} `+$t('page.common.Description'),
      rules: z.string().max(250,$t('admin.maxChars', { length: 250 })),
    },
     {
      component: 'Input',
      defaultValue: 'DISCOVER MORE THRILLS',
      componentProps: {
        placeholder: $t('page.common.Please Enter')+' ('+$t('admin.maxChars', { length: 60 })+'）',
      },
      fieldName: 'discover',
      label: `${routeTitle} `+$t('admin.Found'),
      rules: z.string().max(60,$t('admin.maxChars', { length: 60 })),
    },
    // {
    //   component: 'Input',
    //   defaultValue: '',
    //   componentProps: {
    //     placeholder: '请输入',
    //   },
    //   fieldName: 'link',
    //   label: `${routeTitle}地址`,
    // },
    {
      component: 'Select',
      fieldName: 'link',
      label: $t('admin.redirectUrl'),
      slots:{default:'link'}
    },
    {
        component: 'Select',
        defaultValue: '',
        dependencies: {
          disabled(values) {
           // return linkType.value=='系统页面';
          },
          triggerFields: ['linkType'],
        },
        componentProps: {
            class: 'w-full',
             options: [
                 {
                  label:'',
                  value:'',
                },
                {
                  label:'All Models',
                  value:'#modelall',
                }
                ,
                {
                    label: 'Mid-Size Models',
                    value: '?type=mid#modelall',
                },
                {
                    label: 'Full-Size Models',
                    value:  '?type=full#modelall',
                },
                {
                    label: 'HYBRID Models',
                    value:  '?type=hybrid#modelall',
                },
             ]
        },
        fieldName: 'models',
        label: $t('admin.redirectPosition'),
    },
 

    {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
        tips:'937px-795px'
      },
      fieldName: 'images',
      label: $t('admin.vehicleImage'),
    },
       
  ],
});

async function onSubmit() {
  const values: any = state.form;


  let response;
  values.target_type=linkType.value;
  values.target_value=init_url.value;
  if(!values.link){
    values.link = init_url.value
  }
  if (values.id) {
    response = await putPage_vechile(values);
  } else {
    delete values.id;
    response = await postPage_vechile(values);
  }

  const { code, msg } = response;

  if (code === 1) {
    message.success(msg || 'Success');
    
    formModalApi.close();
    BasicFormApi.resetForm();
     state.form={};
    
    
    //router.push({ name: 'Homevechile' });
  } else {
    message.error(msg || 'Fail'); 
  }
}


async function onGetPage(id: number) {
  const { data } = await getPageInfo_vechile({ id });
  data.post = {
    id: data?.id ?? undefined,
    title: data?.title ?? '',
    des: data?.des ?? '',
    news_content: data?.news_content ?? '',
    images: data?.images ?? [{url:'',id:''}],
    discover: data?.discover ?? '',
    category:data?.category??'',
    link:data?.link??'',
    models:data?.models??''
  };
  state.form = data.post;
  BasicFormApi.setValues({ ...state.form});
  state.pageThemeFiles = data.pageThemeFiles;

  linkType.value = data.target_type
  handleSearch( data.target_value_label)
  if( data.target_value){
        init_url.value = linkType.value!=='自定义页面'?parseInt( data.target_value): data.target_value;
  }else{
    init_url.value='';
  }
}
onMounted(async () => {
  
  if(index.value>0){
          await onGetPage(index.value);
  }
  
});


const linkType = ref('');
const linkOptions = ref<SelectOption[]>([]);
const init_url = ref('');

function handleSelectChange(){
  handleSearch('');
  init_url.value='';
}

async function handleSearch(value: string){

  if (linkType.value === '系统页面') {
          const { data } = await  getPage({
              page: 1,
              limit: 20,
              keyword:value
          });

          linkOptions.value = data.list.map(item => ({
              label: item.name,  
              value: item.id 
          }));
          return;
  }else if(linkType.value == '新闻详情'){
    const { data } = await getNews({
          page: 1,
          limit: 20,
          keyword:value
    });

    linkOptions.value = data.list.map(item => ({
        label: item.news_title,  // name 作为 label
        value: item.id     // id 作为 value
    }));


    return;
  }else if(linkType.value == '广宣品详情'){
        const { data } = await getArticle({
          page: 1,
          limit: 20,
          code:'article',
          keyword:value
        });

     linkOptions.value = data.list.map(item => ({
        label: item.post_title,  // name 作为 label
        value: item.id     // id 作为 value
    }));   
  }else if(linkType.value == '配件详情'){
     const { data } = await getArticle({
          page: 1,
          limit: 20,
          code:'parts',
          keyword:value
        });

     linkOptions.value = data.list.map(item => ({
        label: item.post_title,  // name 作为 label
        value: item.id     // id 作为 value
    }));   
  }
}
</script>

<template>
<Modal :title="state.form.title">
 <Page>
    <Card :title="`${routeTitle} `+$t('page.common.Details')">
      <BasicForm>
        <template #link="{ row }">
          <template class="flex" style="gap:1rem"> 
               <Select v-model:value="linkType" :placeholder="$t('page.common.Please Select')" style="width: 150px" @update:value="handleSelectChange">
                   <SelectOption value="系统页面">{{$t('admin.systemPage')}}</SelectOption>
                   <SelectOption value="新闻详情">{{$t('admin.newsDetail')}}</SelectOption>
                   <SelectOption value="广宣品详情">{{$t('admin.promotionDetail')}}</SelectOption>
                   <SelectOption value="配件详情">{{$t('admin.partsDetail')}}</SelectOption>
                   <SelectOption value="自定义页面">{{$t('admin.customPage')}}</SelectOption>
               </Select>


                  <Select
                      v-if="linkType !== '自定义页面'"
                      :options="linkOptions"
                      v-model:value="init_url"
                      :showSearch="true"
                      :filterOption="false"  
                      :placeholder="$t('page.common.Please Select')"
                      style="width: 240px"
                      @search="handleSearch"
                    />


                    <Input
                      v-if="linkType === '自定义页面'"
                      v-model:value="init_url"
                      :placeholder="$t('page.common.Please Enter')"
                      style="width: 240px"
                    />


              
               <!---这里是一个下拉框，根据不同选择，然后去后台不同接口拉去数据，填充在这里，link的值就是这里选择的值， 或者input输入的值-->
          </template>
      </template>
      </BasicForm>
      
    </Card>
  </Page>
</Modal>
 
</template>
